package com.linxs.topcham.intefaces.controller.admin.org;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.linxs.topcham.application.fnas.FansService;
import com.linxs.topcham.application.fnas.KdtapiService;
import com.linxs.topcham.application.fnas.impl.KdtApiClient;
import com.linxs.topcham.application.org.AgencyOrgService;
import com.linxs.topcham.application.task.OrderService;
import com.linxs.topcham.domain.fans.Order;
import com.linxs.topcham.domain.org.AgencyOrg;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller
@RequestMapping(value = "/admin") 
public class OrgCommissions {
	
	@Autowired
	private AgencyOrgService orgService;
	
	@Autowired
	private KdtapiService apiService;
	
	@Autowired
	private FansService fansService;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/updateorderrecord", method = RequestMethod.GET) 
	public String update() {
		
		for(Order o : orderService.queryAllOrder()) {
			updateData(o.getOrderId()); 
			
		}
		
		return "success";
		
	}
	
	@RequestMapping(value = "/commissions-details/{id}", method = RequestMethod.GET)
	public String currentDetails(@PathVariable("id") String id, Model model) {
		AgencyOrg org = orgService.get(id);
		model.addAttribute("org", org); 
		model.addAttribute("orders", commissions(id));
		return "org/commissionsDetails";
	}
	
	private List<Order> commissions(String id) {
		AgencyOrg org = orgService.get(id);
		
		List<Order> orders = orderService.queryFinishOrderOfOrg(org.getId());
		
		for(Order order : orders) {
			if (null != org) {
				if (order.getAddress().indexOf(org.getAreas()) != -1 || "全国地区".equals(org.getAreas())) {
					order.setBase("0.05");
					order.setCommission(new BigDecimal("0.05").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));
				} else {
					order.setBase("0.03");
					order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));
				}
				order.setOrgId(org.getId());
			} else {
				order.setBase("0.03");
				order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
						.setScale(2, BigDecimal.ROUND_DOWN));

			}
		}
		
		return orders;
	}
	
	@RequestMapping(value = "/commissions-export/{id}", method = RequestMethod.GET) 
	@SuppressWarnings("deprecation")
	public void commissionsExport(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {
		String path = request.getRealPath("/");
		String docName = "当月销售签收订单.xls";
		String templateName = "currentMonthOrderRecord.ftl";
		path = path + "/WEB-INF/views/";
		File documentFile = new File(path + docName);
		Map<String, Object> data = new HashMap<String, Object>();
		
		List<Order> result = commissions(id);
		data.put("orders", result);
		exportToDocumentTemplate(path, templateName, documentFile, data);
		download(request, response);
	}

	private void download(HttpServletRequest request, HttpServletResponse response) {
		try {

			response.setContentType("text/html;charset=UTF-8");
			request.setCharacterEncoding("UTF-8");
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;

			String ctxPath = request.getSession().getServletContext().getRealPath("/");
			String downLoadPath = ctxPath + "/WEB-INF/views/当月销售签收订单.xls";

			long fileLength = new File(downLoadPath).length();

			String agent = request.getHeader("User-Agent");
			String fileName = "当月销售签收订单.xls";
			boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
			if (isMSIE) {
				fileName = java.net.URLEncoder.encode(fileName, "UTF8");
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}

			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bis.close();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void exportToDocumentTemplate(String path, String templateName, File outFile, Map<String, Object> map) {

		Configuration cfg = new Configuration();
		Template template = null;
		Writer out = null;
		try {
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setDefaultEncoding("UTF-8");
			template = cfg.getTemplate(templateName);
			template.setEncoding("UTF-8");
			out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
			template.process(map, out);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();

			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}

	}

	
	
	
	
	public void updateData(String tid) {
//		kdt.trade.get
		
		String method = "kdt.trade.get";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("fields", "receiver_state,receiver_city,receiver_district,receiver_address");		
		params.put("tid", tid);
		
		KdtApiClient kdtApiClient;
		HttpResponse response;

		try {
			Properties props = new Properties();
			props = PropertiesLoaderUtils.loadAllProperties("kdtapp.properties");
			kdtApiClient = new KdtApiClient(props.getProperty("APP_ID"), props.getProperty("APP_SECRET"));

			response = kdtApiClient.get(method, params);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}

			JSONObject json = new JSONObject(result.toString());
			JSONObject obj = new JSONObject(json.getString("response"));
			JSONObject item = new JSONObject(obj.getString("trade"));
			String address = item.getString("receiver_state") + item.getString("receiver_city") + item.getString("receiver_district") + item.getString("receiver_address"); ; 
			Order o = new Order();
			o.setOrderId(tid);
			o.setAddress(address); 
			orderService.updateAddress(o);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
